/**
 * 创元汇 - WebName
 * https://menger.me
 * @大梦
 */

import React, {Component} from 'react'
import {
    Text,
    View,
    Image,
    TextInput,
    ScrollView,
    StyleSheet,
    TouchableOpacity,
    StatusBar
} from 'react-native'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import NetRequest from '../../utils/utilsRequest'
import ServicesApi from '../../constants/ServicesApi'
import GlobalStyles from '../../constants/GlobalStyles'
import NavigationBar from '../../components/common/NavigationBar'
import UtilsView from '../../utils/utilsView'
import { toastShort, consoleLog, toastLong } from '../../utils/utilsToast'
import {Linking} from 'react-native'
import SYImagePicker from 'react-native-syan-image-picker'
import RNFetchBlob from 'react-native-fetch-blob'
const options = {
    imageCount: 1,             // 最大选择图片数目，默认6
    isCamera: true,            // 是否允许用户在内部拍照，默认true
    isCrop: false,             // 是否允许裁剪，默认false
    CropW: ~~(GlobalStyles.width * 0.6),    // 裁剪宽度，默认屏幕宽度60%
    CropH: ~~(GlobalStyles.width * 0.6),    // 裁剪高度，默认屏幕宽度60%
    isGif: false,              // 是否允许选择GIF，默认false，暂无回调GIF数据
    showCropCircle: false,     // 是否显示圆形裁剪区域，默认false
    circleCropRadius: GlobalStyles.width/2,  // 圆形裁剪半径，默认屏幕宽度一半
    showCropFrame: true,       // 是否显示裁剪区域，默认true
    showCropGrid: false,       // 是否隐藏裁剪区域网格，默认false
    quality: 60,                // 压缩质量
};
export default class Gerenxinxi extends Component {

    constructor(props) {
        super(props);
        const { params } = this.props.navigation.state;
        this.state =  {
            advisor_id: global.user.userData.advisor_id,
            advisor_name: global.user.userData.advisor_name,
            advisor_mobile: global.user.userData.advisor_mobile,
            head_img: global.user.userData.head_img,
            nickname: global.user.userData.nickname,
            addr: global.user.userData.addr,
            email: global.user.userData.email,
        }
        // this.netRequest = new NetRequest();
    }

    componentDidMount(){
        
    }

    onBack = () => {
        this.props.navigation.state.params.onCallBack();
        this.props.navigation.goBack();
    }

    componentWillUnmount = () => {
        this.onBack();
    }

    updateState= (state) => {
        if (!this) { return };
        this.setState(state);
    }

    onPushNavigator = (compent, back_msg) => {
        const { navigate } = this.props.navigation;
        navigate( compent , {
            back_msg: back_msg,
            advisor_id: this.state.advisor_id,
            advisor_name: this.state.advisor_name,
            advisor_mobile: this.state.advisor_mobile,
            onCallBack:(gid, gname, gmobile)=>{
                this.updateState({
                    advisor_id: gid,
                    advisor_name: gname,
                    advisor_mobile: gmobile,
                })
            }
        })
    }

    submit = () => {
        let url = ServicesApi.put_member_info;
        let data = {
            nickname: this.state.nickname,
            head_img: this.state.head_img,
            email: this.state.email,
            addr: this.state.addr,
            advisor_id: this.state.advisor_id,
            member_id: global.user.userData.id,
            token: global.user.userData.token,            
        };

        Services.post(url, data, true)
            .then( result => {
                if (result && result.code == StatusCode.SUCCESS_CODE) {
                    // console.log(result);
                    toastShort(result.msg);
                }else{
                    toastLong(result.msg);
                }
            })
            .catch( error => {
                console.log(error)
                toastShort('服务器请求失败，请稍后重试！');

            })
    }

    setPhoto = () => {
        SYImagePicker.showImagePicker(options, (err, selectedPhotos) => {
             if (err) {
                 // 取消选择
                 // console.log('您已取消选择');
                 return;
             }
             // 选择成功
             // console.log('您已选择成功');
             // console.log(selectedPhotos);
             this.photoResult(selectedPhotos);
        }) 
    }

    photoResult = (datas) => {
        let photoList = [],
            selectedPhotos = datas;

        // let url = ServicesApi.base + ServicesApi.photoupload,
        let url = ServicesApi.photoupload,
            thisSelectedPhoto = selectedPhotos[0].uri;


        RNFetchBlob.fetch('POST', url, {

        }, RNFetchBlob.wrap(thisSelectedPhoto)).then((res) => {
            const result = res.json()
            console.log(result)
            if (result && result.code == StatusCode.SUCCESS_CODE) {
                this.updateState({
                    head_img: result.data
                })
            } else {
                toastShort(result.msg);
            }
        }).catch((err) => {
            console.log(err)
        })

    }

    getPhone = () => {
        let phone = this.state.advisor_mobile;
        let url = 'tel: ' + phone;
        Linking.canOpenURL(url)
            .then(supported => {
                if (!supported) {
                    console.log('Can\'t handle url: ' + url);
                } else {
                    return Linking.openURL(url);
                }
            })
            .catch((err)=>{
                console.error('An error occurred', err)
            });

        return phone;
    }

    render(){
        let navigationBar = {
            backgroundColor: '#fff',
            borderBottomColor: '#f2f2f2',
            borderBottomWidth: 1
        }
        return (
            <View style={styles.container}>
                <NavigationBar
                    title = {'个人信息'}
                    style = {navigationBar}
                    titleStyle = {{color: '#333333'}}
                    leftButton = {UtilsView.getLeftBlackButton(() => this.onBack())}
                />
                <StatusBar
                    animated = {true}
                    hidden = {false}
                    backgroundColor = {'transparent'}
                    translucent = {true}
                    barStyle = {'dark-content'}
                />
                <KeyboardAwareScrollView keyboardShouldPersistTaps={'handled'}>
                    <View style={[GlobalStyles.whiteModule, {marginTop: 10}]}>
                        <TouchableOpacity onPress={() => {this.setPhoto()}} style={GlobalStyles.userlist}>
                            <View style={GlobalStyles.userlistright}>
                                <Text style={GlobalStyles.userlisttext}>头像</Text>
                                {this.state.head_img ? 
                                    <Image source={{uri: this.state.head_img}} style={styles.userPhoto} />
                                    : null}
                                <Image source={require('../../assets/images/icons/icon_user_arrow.png')} style={GlobalStyles.userlistmore} />
                            </View>
                        </TouchableOpacity>
                        <View style={GlobalStyles.userlist}>
                            <View style={GlobalStyles.userlistright}>
                                <Text style={GlobalStyles.userlisttext}>昵称</Text>
                                <TextInput
                                    placeholder={this.state.nickname ? this.state.nickname : '请填写昵称' }
                                    onChangeText={(text) => {
                                        this.updateState({
                                            nickname: text
                                        })
                                    }}
                                    style={[GlobalStyles.cellInput, GlobalStyles.isIOS ? null : styles.inputAndroid, {textAlign: 'right', color: '#bbbbc1', fontSize: 14, width: 210}]} 
                                    underlineColorAndroid={'transparent'}
                                >
                                </TextInput>
                            </View>
                        </View>
                        <View style={GlobalStyles.userlist}>
                            <View style={GlobalStyles.userlistright}>
                                <Text style={GlobalStyles.userlisttext}>手机号</Text>
                                <Text style={GlobalStyles.userlistRightText}>{global.user.userData.account}</Text>
                            </View>
                        </View>    
                        <View style={GlobalStyles.userlist}>
                            <View style={GlobalStyles.userlistright}>
                                <Text style={GlobalStyles.userlisttext}>地址</Text>
                                <TextInput
                                    placeholder={this.state.addr ? this.state.addr : '请填写真实地址' }
                                    onChangeText={(text) => {
                                        this.updateState({
                                            addr: text
                                        })
                                    }}
                                    style={[GlobalStyles.cellInput, GlobalStyles.isIOS ? null : styles.inputAndroid, {textAlign: 'right', color: '#bbbbc1', fontSize: 14, width: 210}]} 
                                    underlineColorAndroid={'transparent'}
                                >
                                </TextInput>
                            </View>
                        </View>    
                        <View style={GlobalStyles.userlist}>
                            <View style={GlobalStyles.userlistright}>
                                <Text style={GlobalStyles.userlisttext}>邮箱</Text>
                                <TextInput
                                    placeholder={this.state.email ? this.state.email : '请填写常用邮箱' }
                                    onChangeText={(text) => {
                                        this.updateState({
                                            email: text
                                        })
                                    }}
                                    style={[GlobalStyles.cellInput, GlobalStyles.isIOS ? null : styles.inputAndroid, {textAlign: 'right', color: '#bbbbc1', fontSize: 14, width: 210}]} 
                                    underlineColorAndroid={'transparent'}
                                >
                                </TextInput>
                            </View>
                        </View>

                        {this.state.advisor_id ?
                            <TouchableOpacity onPress={()=>this.getPhone()} style={GlobalStyles.userlist}>
                                <View style={GlobalStyles.userlistright}>
                                    <Text style={GlobalStyles.userlisttext}>{global.user.userData.is_up_advisor == 1 ? '联系财富顾问' : '财富顾问'}</Text>
                                    <Text style={[styles.userlistRightText, {right: 0}]}>{this.state.advisor_name}({this.state.advisor_mobile})</Text>
                                </View>
                            </TouchableOpacity>
                        : null } 

                        {global.user.userData.is_up_advisor == 1 ?
                            <TouchableOpacity onPress={()=>{this.onPushNavigator('Caifuguwen')}} style={GlobalStyles.userlist}>
                                <View style={GlobalStyles.userlistright}>
                                    <Text style={GlobalStyles.userlisttext}>{this.state.advisor_id ? '更换财富顾问' : '选择财富顾问'}</Text>
                                    <Text style={styles.userlistRightText}></Text>
                                    <Image source={require('../../assets/images/icons/icon_user_arrow.png')} style={GlobalStyles.userlistmore} />
                                </View>
                            </TouchableOpacity> 
                        : null }
                        
                    </View>

                    

                    <View style={[GlobalStyles.whiteModule, {marginTop: 10}]}>
                        <TouchableOpacity onPress={() => {this.onPushNavigator('SetMima')}} style={GlobalStyles.userlist}>
                            <View style={[GlobalStyles.userlistleft, GlobalStyles.hide]}>
                                <Image source={require('../../assets/images/icons/icon_member_mimaguanli.png')} style={GlobalStyles.usericon} />
                            </View>
                            <View style={GlobalStyles.userlistright}>
                                <Text style={GlobalStyles.userlisttext}>密码管理</Text>
                                <Image source={require('../../assets/images/icons/icon_user_arrow.png')} style={GlobalStyles.userlistmore} />
                            </View>
                        </TouchableOpacity>    
                        
                    </View>

                    <TouchableOpacity onPress={() => {this.submit()}} style={GlobalStyles.submit}>
                        <Text style={GlobalStyles.btna}>保存信息</Text>
                    </TouchableOpacity>
                </KeyboardAwareScrollView>
            </View>
        );
    }


}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: GlobalStyles.bgColor,
    },
    userlistRightText: {
        position: 'absolute',
        right: 20,
        color: '#585858',
    },
    userPhoto: {
        width: 32,
        height: 32,
        position: 'absolute',
        right: 20,
        borderRadius: 16,
    }
});
